<template>
  <div class="header">
    <el-menu
      :default-active="activeIndex2"
      class="el-menu-demo"
      mode="horizontal"
      background-color="#545c64"
      text-color="#fff"
      ><div :index="item.name" v-for="item in routerList" :key="item.name" class="son">
        <el-menu-item :index="item.name" @click="handleSelect($event, item.name)">{{
          item.title
        }}</el-menu-item>
        <el-icon @click="close(item)"><Close /></el-icon>
      </div>

      <el-sub-menu index="CLOSE" style="position: absolute; right: 18px">
        <template #title>操作</template>
        <el-menu-item @click="handleSelect($event, 'EDIT')" index="EDIT">退出</el-menu-item>
        <el-menu-item @click="handleSelect($event, 'CHANGE_PASSWORD')" index="CHANGE_PASSWORD"
          >修改密码</el-menu-item
        >
        <el-menu-item @click="handleSelect($event, 'CLOSE_ALL')" index="CLOSE_ALL"
          >全部清除</el-menu-item
        >
      </el-sub-menu>
    </el-menu>
  </div>
</template>

<script lang="ts" setup>
import { Close } from '@element-plus/icons-vue'
import useStore from '../../stores/user'
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import router from '@/router'

import { routerPath } from '@/router/utils/routeConfig'
import { useRoute } from 'vue-router'
import { sessionClear } from '@/utils/sessionStorage'
const state = reactive({
  routerList: []
})
const route = useRoute()
watch(
  () => route.name,
  () => {
    state.routerList = JSON.parse(sessionStorage.getItem('_router')) || []
  },
  { immediate: true }
)

onMounted(() => {
  state.routerList = JSON.parse(sessionStorage.getItem('_router'))
})
const store = useStore()
const activeIndex2 = ref('1')
const handleSelect = (event, key) => {
  if (key === 'EDIT') {
    router.push({ name: 'login' })
    sessionClear()
    return
  }
  if (key === 'CLOSE_ALL') {
    store.routerAllClosePinia()
    return router.push('/')
  }
  router.push(routerPath[key])
}

// 关闭当前页面
const close = (value) => {
  if (route.name === value.name) {
    return router.push(store.routerRemovePinia(value))
  } else {
    store.routerRemovePinia(value)
    state.routerList = JSON.parse(sessionStorage.getItem('_router'))
  }
}

const { routerList } = toRefs(state)
</script>
<style lang="scss" scoped>
.header {
  width: 100%;
  height: 60px;
  .son {
    display: flex;
    align-items: center;
    height: 100%;
  }
  .son:hover {
    background: #434a50;
  }
}
</style>
